const utils=require("../../utils/util.js");
const app=getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    isUserLogin:false,
    page: 1,
    pageSize: 5,
    total: 0,   //总记录条数  
    hasMoreData: true,
    contentlist: [],
    shopid: 0,
    tipText: '',
    isLoadingMore: false,  //是否正在加载更多数据
    hasData:true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {    
    var that = this;   
    //that.getInitData();  
    that.getInitData();
  },
  getInitData:function(){
    var that = this;
    var isUserLogin = utils.isUserLogin();
    that.setData({
      isUserLogin: isUserLogin,
      shopid: utils.getUserId()
    });
    if (isUserLogin) {
      that.getMessageInfo();
      that.setMessageStatus();
    }
  },
  /**
 * 生命周期函数--监听页面显示
 */
  onShow: function () {
    var that = this;
    // utils.checkLogin(function () {
    //   if(app.globalData.hasNewMessage){
    //     that.getMessageInfo();
    //     that.setMessageStatus();
    //     wx.pageScrollTo({
    //       scrollTop: 0,
    //     });
    //     app.globalData.hasNewMessage=false;
    //   }

    // }, function () {
    //   wx.redirectTo({
    //     url: '../my/login/login',
    //   })
    // });
    var isUserLogin = utils.isUserLogin();
    that.setData({
      isUserLogin: isUserLogin,
      shopid: utils.getUserId()
    });
    if (app.globalData.hasNewMessage) {
      that.getMessageInfo();
      that.setMessageStatus();
      wx.pageScrollTo({
        scrollTop: 0,
      });
      app.globalData.hasNewMessage = false;
    }
    
  },
  /**
   * 登录
   */
  bindTapLogin:function(e){
    var that = this;
    wx.showLoading({
      title: '正在登录',
    })
    wx.login({
      success: function (res) {
        if (res.code) {
          //发起网络请求
          wx.request({
            url: utils.apiUrl + '/shop/GetWxLoginInfo',
            data: {
              code: res.code
            },
            success: function (response) {
              var data = response.data;
              if (data.status == 0) {
                //如果已存在此用户，则根据状态跳转到对应的页面
                if (data.data.ShopID > 0) {
                  utils.setUserId(data.data.ShopID);
                  that.getInitData();
                } else {//否则走注册用户流程
                  var openid = data.data.OpenId;
                  var sessionKey = data.data.WxSessionKey;
                  wx.navigateTo({
                    url: '/pages/my/binduser/binduser?openid=' + openid,
                  })
                }
              }
            },
            fail: function () {
              
            },
            complete: function () {
              wx.hideLoading();
            }
          });
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    });
  },
 /**
  * 获取消息信息
  */
  getMessageInfo: function () {
    var that = this;

    that.setData({
      page:1,
      total:0,
      tipText: '',
      contentList:[]
    });
    var data = {
      shopId: that.data.shopid,
      pageIndex: that.data.page,
      pageSize: that.data.pageSize
    }

    utils.getData(utils.apiUrl + "/Message/SearchListPageByShopId", data, function (res) {
      if (res.status == 0) {      
        var contentlist = res.data.List;
        var total = res.data.Total;
        var hasMore = false;
        var hasData = false;
        if (contentlist.length < total) {
          hasMore = true;
        }      
        if(total>0)
        {
          hasData=true;
        }
        that.setData({
            contentlist: contentlist,
            hasMoreData: hasMore,
            total: total,
            hasData: hasData
        })
        
      } else {
        wx.showToast({
          title: '查询失败',
          icon: 'none'
        })
      }
    }, function (res) {
      wx.showToast({
        title: '加载数据失败',
        icon: 'none'
      })

    })
    //wx.hideLoading();
  },
  /**
   * 设置消息状态
   */
  setMessageStatus: function () {
    var that = this
    var data = {};   
    utils.postData(utils.apiUrl + "/Message/SetMessageStatus", data, function (res) {
      if(res.status==0){
        wx.removeTabBarBadge({
          index:2
        });
      }
    });
   
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },
  /**
   * 店铺链接
   */
  bindTapShopLink: function (e) {
    var shopId = e.currentTarget.dataset.shopid;
    var url = '../carcircle/othermy/othermy?shopid=' + shopId;
    utils.safeOpenUrl(url);
  },
  /**
   * 打电话
   */
  bindTapPhone:function(e){
      var index=e.currentTarget.dataset.index;
      var oInfo = this.data.contentlist[index];
      wx.makePhoneCall({
        phoneNumber: oInfo.TriggerShopMobile,
      })
  },
  /**
   * 动态链接
   */
  bindTapQuote:function(e){
    var index = e.currentTarget.dataset.index;
    var oPost = this.data.contentlist[index];
    if (oPost.MessageType< 4 &&(oPost.PostType==1 || oPost.PostType==2)){
       wx.navigateTo({
         url: '/pages/carcircle/carcircledetails/carcircledetails?posttype='+oPost.PostType+"&postid="+oPost.PostID
       })
    }
    else if(oPost.MessageType==4){
      wx.navigateTo({
        url: '/pages/my/shopdetail/shopdetail?shopid=' + oPost.ShopId
      })
    }

  },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    var that = this
    that.data.page = 1
    that.getMessageInfo(that.data.shopid);
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var that = this
    if (!that.data.hasMoreData) {
      that.setData({
        tipText: "没有更多数据了"
      });
      return;
    }
    else {
      that.setData({
        tipText: "正在加载更多数据.."
      });
      if (that.data.isLoadingMore) {
        return;
      }
      that.setData({
        page: that.data.page + 1,
        isLoadingMore: true
      });
      utils.getData(
        utils.apiUrl + '/Message/SearchListPageByShopId', 
        {
          shopId: that.data.shopid,
          pageIndex: that.data.page,
          pageSize: that.data.pageSize
        },
        function (response) {
          if (response.status == 0) {
            var tempList = that.data.contentlist;
            var data = response.data;
            var result = data.List;
            var total = data.Total;
            var listCombine = tempList.concat(result);
            var hasMoreData = false;
            if (listCombine.length < total) {
              hasMoreData = true;
            }
            that.setData({
              contentlist: listCombine,
              isLoadingMore: false,
              hasMoreData: hasMoreData
            });
          }
        },
        function () { },
        function () {
          wx.hideLoading();
        }
      );
    }
  },

  /**
  * 用户点击右上角分享
  */
  onShareAppMessage: function (res) {
    if (res.from === 'menu') {
      // 来自页面右上角转发按钮
      return {
        title: '快来上车务圈，更多人脉，更多订单！限时免费注册！',
        path: '/pages/index/index',
        imageUrl: '/imgs/share-banner.jpg'
      };
    }
  }
})